<?php
namespace App\Http\Controllers\Laifei\Work;

use App\Http\Controllers\Controller;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LaifeiWorkFeedbackController extends Controller
{
    protected $hang_id;
    protected $feedback_remark;
    protected $hang_message;
    protected $work_message;

    public function index()
    {

        $all = $this->all;
        $feedback = $all['feedback'];
        $this->hang_id = $all['hang_id'];
        $this->feedback_remark = $all['feedback_remark'];

        try{
            DB::beginTransaction();
            // 查询这个申诉
            $this->hang_message = DB::table('explore_hang_up')->where('hang_id','=',$this->hang_id)->lockForUpdate()->first();
            $this->hang_message = json_decode(json_encode($this->hang_message), true);
            $this->work_message = DB::table('explore_work as ew')
                ->leftJoin('shop','ew.shop_id','=','shop.shop_id')
                ->leftJoin('lottery_users as lu1','ew.apply_we_id','=','lu1.we_id')
                ->leftJoin('lottery_users as lu2','ew.receiver_we_id','=','lu2.we_id')
                ->leftJoin('talent','lu2.we_id','=','talent.we_id')
                ->where('work_id','=',$this->hang_message['work_id'])
                ->select('ew.work_id','ew.work_no','shop.shop_name','lu1.openid as apply_openid','lu2.openid as receiver_openid','talent.account_name')
                ->get()
                ->toArray();;
            $this->work_message = json_decode(json_encode($this->work_message), true);
            $this->work_message = $this->work_message[0];

            if($this->hang_message['is_delete'] !== 0){
                DB::rollBack();
                return $this->setReturnJson(-1,'申诉状态已改变，请刷新当前页面');
            }

            // 更新挂起单
            DB::table('explore_hang_up')->where('hang_id','=',$this->hang_id)->update([
                'is_delete'=>1,
                'feedback'=>$feedback,
                'feedback_remark'=>$this->feedback_remark,
                'feedback_at'=>date('Y-m-d H:i:s'),
            ]);

            if ($feedback === 1) { // 支持商家:驳回达人的申诉
                self::feedbackRefuse();
            } else { // 支持达人:验收成功
                self::feedbackAccept();
            }

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            Log::error(LaifeiWorkFeedbackController::class,['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1,'审核失败',['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
        return $this->setReturnJson(0,'审核成功');

    }

    /**
     * 驳回达人申诉（继续）
     */
    protected function feedbackRefuse()
    {
        DB::table('explore_work')
            ->where('work_id', '=', $this->work_message['work_id'])
            ->update(['hang_up'=>2]);
        DB::table('explore_work_log')->insert([
            'work_id' => $this->work_message['work_id'],
            'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_FEEDBACK_REFUSE,
            'user_id' => $this->userInfo['id'],
            'remark' => '管理员【' . $this->userInfo['name'] . '】拒回用户申诉，审核备注：' . $this->feedback_remark,
        ]);

        //  发送验收拒回微信通知（发送给达人）
        $data = [
            'first' => '您好，您的申诉请求已被管理员拒回',
            'keyword1' => '您在【'.$this->work_message['shop_name'].'】的申诉经管理员审核，现已驳回',
            'keyword2' => '管理员【'.$this->userInfo['name'].'】',
            'keyword3' => $this->feedback_remark,
            'keyword4' => date('Y-m-d'),
            'remark' => [
                'value' => '请在48小时内重新提交投稿，订单超时将自动取消。',
                'color' => '#F00'
            ],
        ];
        //发送通知
        Common::sendLaifeiMessage($this->work_message['receiver_openid'],'work_reject',$data,'/talent/history?tab=1');

    }

    /**
     * 同意达人申诉
     */
    protected function feedbackAccept()
    {
        DB::table('explore_work')
            ->where('work_id', '=', $this->work_message['work_id'])
            ->update([
                'status' => Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED,
                'accept_time' => date('Y-m-d H:i:s'),
                'accept_user' => $this->userInfo['id'],
                'accept_remark' => $this->feedback_remark,
                'hang_up'=>0,
            ]);
        // 记录日志
        DB::table('explore_work_log')->insert([
            [
                'work_id' => $this->work_message['work_id'],
                'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_FEEDBACK_ACCEPT,
                'user_id' => $this->userInfo['id'],
                'remark' => '管理员【' . $this->userInfo['name'] . '】同意用户申诉，审核备注：' . $this->feedback_remark,
            ],[
                'work_id' => $this->work_message['work_id'],
                'action' => Data::DATA_DB_EXPLORE_WORK_ACTION_ACCEPTED,
                'user_id' => $this->userInfo['id'],
                'remark' => '管理员【' . $this->userInfo['name'] . '】验收投稿，验收备注：' . $this->feedback_remark,
            ]
        ]);

        //  发送验收拒回微信通知（发送给商家）
        $data = [
            'first' => '您好，您的验收已被管理员拒回',
            'keyword1' => '您在【'.$this->work_message['shop_name'].'】的验收操作经达人【'.$this->work_message['account_name'].'】申诉，现已驳回',
            'keyword2' => '管理员【'.$this->userInfo['name'].'】',
            'keyword3' => $this->feedback_remark,
            'keyword4' => date('Y-m-d'),
            'remark' => '当前此工单状态为已验收通过。',
        ];
        //发送通知
        Common::sendLaifeiMessage($this->work_message['apply_openid'],'work_reject',$data,'/history?tab=1');

        //  发送验收通过微信通知（发送给达人）
        $data = [
            'first' => '您好，您的验收申诉已被管理员通过',
            'keyword1' => $this->work_message['work_no'],
            'keyword2' => date('Y-m-d'),
            'keyword3' => '通过',
            'keyword4' => '您在店铺【'.$this->work_message['shop_name'].'】发起的申诉，已被管理员通过。',
            'keyword5' => '管理员【'.$this->userInfo['name'].'】',
            'remark' => '当前此工单状态为已验收通过，请耐心等待结算。',
        ];
        //发送通知
        Common::sendLaifeiMessage($this->work_message['receiver_openid'],'work_check',$data,'/talent/history?tab=1');

    }

}
